//
//  MapViewController.m
//  AnjukeBroker_New
//
//  Created by shan xu on 14-3-18.
//  Copyright (c) 2014年 Wu sicong. All rights reserved.
//

#import "MapViewControllers.h"
#import "RegionAnnotation.h"
//#import "RegexKitLite.h"
#import "CheckInstalledMapAPP.h"
//#import "LocationChange.h"
//#import "LocIsBaidu.h"
//#import "NSString+RTStyle.h"

#define SYSTEM_NAVIBAR_COLOR [UIColor colorWithRed:0 green:0 blue:0 alpha:1]
#define ISIOS7 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7)
#define ISIOS6 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=6)
#define STATUS_BAR_H 20
#define NAV_BAT_H 44

#define FRAME_WITH_NAV CGRectMake(0, 0, [self windowWidth], [self windowHeight] - STATUS_BAR_H - NAV_BAT_H)
#define FRAME_USER_LOC CGRectMake(8, [self windowHeight] - STATUS_BAR_H - NAV_BAT_H-58+64, 40, 40)
#define FRAME_CENTRE_LOC CGRectMake([self windowWidth]/2-8, ([self windowHeight] - STATUS_BAR_H - NAV_BAT_H)/2-25+64, 16, 33)


@interface MapViewControllers ()
//导航目的地2d,百度
@property(nonatomic,assign) CLLocationCoordinate2D naviCoordsBd;
//导航目的地2d,高德
@property(nonatomic,assign) CLLocationCoordinate2D naviCoordsGd;
//user最新2d
@property(nonatomic,assign) CLLocationCoordinate2D nowCoords;
//最近一次成功查询2d
@property(nonatomic,assign) CLLocationCoordinate2D lastCoords;
//最近一次请求的中心2d
@property(nonatomic,assign) CLLocationCoordinate2D centerCoordinate;
@property(nonatomic,strong) NSMutableArray *requestLocArr;
@property(nonatomic,strong) MKMapView *regionMapView;
//updateInt初始化为0，大于1时，didUpdateUserLocation中setRegion不再执行
@property(nonatomic,assign) int updateInt;
//userRegion 地图中心点定位参数
@property(nonatomic,assign) MKCoordinateRegion userRegion;
@property(nonatomic,assign) MKCoordinateRegion naviRegion;

@property(nonatomic,strong) NSString *city;
@property(nonatomic,strong) NSArray *routes;//ios6路线arr
//地图的区域和详细地址
@property(nonatomic,strong) NSString *regionStr;
@property(nonatomic,strong) NSString *addressStr;
@property(nonatomic,strong) CLLocationManager *locationManager;
//定位参数信息
@property(nonatomic,strong) RegionAnnotation *regionAnnotation;
//定位状态，包括6种状态
@property(nonatomic, assign) int loadStatus;
@end

@implementation MapViewControllers
@synthesize mapType;
@synthesize regionMapView;
@synthesize addressStr;
@synthesize updateInt;
@synthesize userRegion;
@synthesize naviRegion;
@synthesize lastCoords;
@synthesize naviCoordsBd;
@synthesize naviCoordsGd;
@synthesize nowCoords;
@synthesize routes;
@synthesize regionStr;
@synthesize navDic;
@synthesize requestLocArr;
@synthesize centerCoordinate;
@synthesize locationManager;
@synthesize regionAnnotation;
@synthesize loadStatus;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.updateInt = 0;
        self.navDic = [[NSDictionary alloc] init];
        self.requestLocArr = [[NSMutableArray alloc] init];
    }
    return self;
}
- (NSInteger)windowWidth {
    return [[[[UIApplication sharedApplication] windows] objectAtIndex:0] frame].size.width;
}
- (NSInteger)windowHeight {
    return [[[[UIApplication sharedApplication] windows] objectAtIndex:0] frame].size.height;
}
- (void)viewDidDisappear:(BOOL)animated{
    self.regionMapView.delegate = nil;
    self.locationManager.delegate = nil;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (ISIOS7) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
    [self addBackButton];
    NSString *titStr;
        titStr = @"位置";
    UIBarButtonItem* barbuttonitem=[[UIBarButtonItem alloc]init];
    barbuttonitem.title=@"";
    barbuttonitem.tintColor=[UIColor blackColor];
    [barbuttonitem setTintColor:[UIColor blackColor]];
    self.navigationItem.backBarButtonItem=barbuttonitem;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 31)];
    lb.backgroundColor = [UIColor clearColor];
    lb.font = [UIFont systemFontOfSize:19];
    lb.textAlignment = NSTextAlignmentCenter;
    lb.textColor = [UIColor whiteColor];
    lb.text = titStr;
    self.navigationItem.titleView = lb;
    
    self.regionMapView = [[MKMapView alloc] initWithFrame:FRAME_WITH_NAV];
    self.regionMapView.delegate = self;
    self.regionMapView.showsUserLocation = YES;
    [self.view addSubview:self.regionMapView];
 
     self.locationManager = [CLLocationManager new];
    [self.locationManager setDelegate:self];
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.locationManager setDistanceFilter:kCLDistanceFilterNone];
    [self.locationManager startUpdatingLocation];
    
    UIButton *goUserLocBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goUserLocBtn.frame = FRAME_USER_LOC;
    [goUserLocBtn addTarget:self action:@selector(goUserLoc:) forControlEvents:UIControlEventTouchUpInside];
    [goUserLocBtn setImage:[UIImage imageNamed:@"wl_map_icon_position.png"] forState:UIControlStateNormal];
    [goUserLocBtn setImage:[UIImage imageNamed:@"wl_map_icon_position_press.png"] forState:UIControlStateHighlighted];
    goUserLocBtn.backgroundColor = [UIColor clearColor];
    [self.view addSubview:goUserLocBtn];
    naviCoordsGd.latitude = [[self.navDic objectForKey:@"google_lat"] doubleValue];
    naviCoordsGd.longitude = [[self.navDic objectForKey:@"google_lng"] doubleValue];


        CLLocation *loc = [[CLLocation alloc] initWithLatitude:naviCoordsGd.latitude longitude:naviCoordsGd.longitude];
        MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(naviCoordsGd, 500, 500);
        self.naviRegion = [self.regionMapView regionThatFits:viewRegion];
        
        [self.regionMapView setRegion:self.naviRegion animated:NO];
        [self showAnnotation:loc coord:naviCoordsGd];

        if (!ISIOS6) {
            [self performSelector:@selector(setRegionAgain) withObject:nil afterDelay:2.0];
        }
   // }
}
-(void)setRegionAgain{
    MKCoordinateRegion viewRegion1 = MKCoordinateRegionMakeWithDistance(naviCoordsGd, 200, 200);
    self.naviRegion = [self.regionMapView regionThatFits:viewRegion1];
    [self.regionMapView setRegion:self.naviRegion animated:NO];
}
-(void)openGPSTips{
    UIAlertView *alet = [[UIAlertView alloc] initWithTitle:@"当前定位服务不可用" message:@"请到“设置->隐私->定位服务”中开启定位" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alet show];
}
#pragma UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (self.mapType == RegionChoose) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)addBackButton {
    // 设置返回btn
    UIImage *image = [UIImage imageNamed:@"anjuke_icon_back.png"];
    UIImage *highlighted = [UIImage imageNamed:@"anjuke_icon_back.png"];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, image.size.width + 40 , 44);
    [button addTarget:self action:@selector(doBack:) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:highlighted forState:UIControlStateHighlighted];
    [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 40)];
    button.titleLabel.font=[UIFont systemFontOfSize:14];
    [button setTitle:@"返回" forState:UIControlStateNormal];
    [button setTitle:@"返回" forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateHighlighted];
    button.titleLabel.textAlignment = NSTextAlignmentLeft;
    button.titleLabel.backgroundColor = [UIColor clearColor];
    button.backgroundColor = [UIColor clearColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}
-(void)doBack:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)rightButtonAction:(id)sender{

    if (lastCoords.latitude && lastCoords.longitude) {
        if (self.siteDelegate && [self.siteDelegate respondsToSelector:@selector(loadMapSiteMessage:)]){
            NSMutableDictionary *locationDic = [[NSMutableDictionary alloc] init];
            [locationDic setValue:self.addressStr forKey:@"address"];
            [locationDic setValue:self.city forKey:@"city"];
            [locationDic setValue:self.regionStr forKey:@"region"];
            [locationDic setValue:[NSString stringWithFormat:@"%.8f",lastCoords.latitude] forKey:@"google_lat"];
            [locationDic setValue:[NSString stringWithFormat:@"%.8f",lastCoords.longitude] forKey:@"google_lng"];
            [locationDic setValue:@"google" forKey:@"from_map_type"];
          
           [self.siteDelegate loadMapSiteMessage:locationDic];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(void)goUserLoc:(id)sender{
    [self.regionMapView setRegion:self.userRegion animated:YES];
}

-(void)doAcSheet{
    NSArray *appListArr = [CheckInstalledMapAPP checkHasOwnApp];
    NSString *sheetTitle = [NSString stringWithFormat:@"导航到 %@",[self.navDic objectForKey:@"address"]];

    UIActionSheet *sheet;
    if ([appListArr count] == 1) {
       sheet = [[UIActionSheet alloc] initWithTitle:sheetTitle delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:appListArr[0], nil];
    }
    sheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [sheet showInView:self.view];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
            CLLocationCoordinate2D to;
      
        
            to.latitude = naviCoordsGd.latitude;
            to.longitude = naviCoordsGd.longitude;
        
            MKMapItem *currentLocation = [MKMapItem mapItemForCurrentLocation];
        
            MKMapItem *toLocation = [[MKMapItem alloc] initWithPlacemark:[[MKPlacemark alloc] initWithCoordinate:to addressDictionary:nil]];
            
            toLocation.name = addressStr;
            [MKMapItem openMapsWithItems:[NSArray arrayWithObjects:currentLocation, toLocation, nil] launchOptions:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeDriving, [NSNumber numberWithBool:YES], nil] forKeys:[NSArray arrayWithObjects:MKLaunchOptionsDirectionsModeKey, MKLaunchOptionsShowsTrafficKey, nil]]];
//          NSLog(@"dsfasdhjklfh---------------%@",   MKLaunchOptionsDirectionsModeKey);
    }
}

#pragma mark - 检测应用是否开启定位服务
- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {
    [manager stopUpdatingLocation];
    switch([error code]) {
        case kCLErrorDenied:
            [self openGPSTips];
            break;
        case kCLErrorLocationUnknown:
            break;
        default:
            break;
    }
}

#pragma mark MKMapViewDelegate -user location定位变化
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    self.nowCoords = [userLocation coordinate];
    //放大地图到自身的经纬度位置。
    self.userRegion = MKCoordinateRegionMakeWithDistance(self.nowCoords, 200, 200);

    if (self.mapType != RegionNavi) {
        if (self.updateInt >= 1) {
            return;
        }
        [self showAnnotation:userLocation.location coord:self.nowCoords];
        [self.regionMapView setRegion:self.userRegion animated:NO];
    }
}
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    if (self.mapType == RegionNavi) {
        return;
    }
    if (ISIOS7) {
        if ([mapView.annotations count]) {
            [mapView removeAnnotations:mapView.annotations];
        }
    }

    if (self.updateInt == 0){
        return;
    }
    self.centerCoordinate = mapView.region.center;
    NSLog(@"dsfasdhjklfh---------------%f-------------------------%f",self.centerCoordinate.latitude,self.centerCoordinate.longitude);
    CLLocation *loc = [[CLLocation alloc] initWithLatitude:self.centerCoordinate.latitude longitude:self.centerCoordinate.longitude];
    
    [self showAnnotation:loc coord:centerCoordinate];
}
- (void)mapView:(MKMapView *)mapView regionWillChangeAnimated:(BOOL)animated{
    if (self.mapType == RegionNavi) {
        return;
    }
    if (ISIOS7) {
        if ([mapView.annotations count]) {
            [mapView removeAnnotations:mapView.annotations];
        }
    }
}
#pragma mark- 获取位置信息，并判断是否显示，block方法支持ios6及以上
-(void)showAnnotation:(CLLocation *)location coord:(CLLocationCoordinate2D)coords{
    self.updateInt += 1;
    if (self.mapType == RegionNavi && ![[self.navDic objectForKey:@"region"] isEqualToString:@""]) {
        loadStatus = 4;
        [self addAnnotationView:location coord:coords region:[self.navDic objectForKey:@"region"]  address:[self.navDic objectForKey:@"address"]];
        return;
    }
    [self.requestLocArr addObject:[NSString stringWithFormat:@"%.8f",[location coordinate].latitude]];
    self.regionStr = @"";
    self.addressStr = @"";
    self.city = @"";
    self.lastCoords = coords;
    if (self.mapType == RegionChoose) {
        loadStatus = 0;
    }else{
        loadStatus = 3;
    }
    [self addAnnotationView:location coord:coords region:@"加载地址中..." address:nil];
    
    //CLGeocoder ios5之后支持
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error) {
        //判断返回loc和当前最后一次请求loc的latitude是否一致，否则不返回位置信息
        if (![[NSString stringWithFormat:@"%0.8f",[location coordinate].latitude] isEqualToString:[NSString stringWithFormat:@"%0.8f",self.centerCoordinate.latitude]] && self.mapType == RegionChoose && self.updateInt >= 2) {
            [self.requestLocArr removeObject:[NSString stringWithFormat:@"%0.8f",[location coordinate].latitude]];
            return;
        }
        if ([self.requestLocArr count] > 0) {
            [self.requestLocArr removeAllObjects];
        }
        if (array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            NSString *region = [placemark.addressDictionary objectForKey:@"SubLocality"];
            NSString *address = [placemark.addressDictionary objectForKey:@"Name"];
            self.regionStr = region;
            self.addressStr = address;
            self.city = placemark.administrativeArea ? placemark.administrativeArea : @"";
            
            if (mapType == RegionChoose) {
                loadStatus = 1;
            }else{
                loadStatus = 4;
            }
            [self addAnnotationView:location coord:coords region:region address:address];
        }else{
            self.regionStr = @"";
            self.addressStr = @"";
            self.city = @"";
            
            if (mapType == RegionChoose) {
                loadStatus = 2;
            }else{
                loadStatus = 5;
            }
            [self addAnnotationView:location coord:coords region:@"没有找到有效地址" address:nil];
        }
    }];
}
#pragma mark- 添加大头针的标注
-(void)addAnnotationView:(CLLocation *)location coord:(CLLocationCoordinate2D)coords region:(NSString *)region address:(NSString *)address{
    if ([self.regionMapView.annotations count]) {
        [self.regionMapView removeAnnotations:self.regionMapView.annotations];
    }

    if (!self.regionAnnotation) {
        self.regionAnnotation = [[RegionAnnotation alloc] init];
    }
   
    self.regionAnnotation.coordinate = coords;
    self.regionAnnotation.title = region;
    self.regionAnnotation.subtitle  = address;
    
    if (loadStatus == 0) {
        self.regionAnnotation.annotationStatus = ChooseLoading;
    }else if (loadStatus == 1){
        self.regionAnnotation.annotationStatus = ChooseSuc;
    }else if (loadStatus == 2){
        self.regionAnnotation.annotationStatus = ChooseFail;
    }else if (loadStatus == 3){
        self.regionAnnotation.annotationStatus = NaviLoading;
    }else if (loadStatus == 4){
        self.regionAnnotation.annotationStatus = NaviSuc;
    }else if (loadStatus == 5){
        self.regionAnnotation.annotationStatus = NaviFail;
    }
    [self.regionMapView addAnnotation:self.regionAnnotation];
    [self.regionMapView selectAnnotation:self.regionAnnotation animated:YES];
}

#pragma mark MKMapViewDelegate -显示大头针标注
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    if ([annotation isKindOfClass:[regionAnnotation class]]) {
        static NSString* identifier = @"MKAnnotationView";
        RegionAnnotationView *annotationView;
        
        annotationView = (RegionAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
        
        if (!annotationView) {
            annotationView = [[RegionAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
            annotationView.acSheetDelegate = self;
        }

        annotationView.backgroundColor = [UIColor clearColor];
        annotationView.annotation = annotation;
        [annotationView layoutSubviews];
        [annotationView setCanShowCallout:NO];
        
        return annotationView;
    }else{
        return nil;
    }
}
-(void)naviClick{
    [self doAcSheet];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
